import storage from '../../utils/Stroage.js'
import config from '../../utils/config.js'
import { Login, getUserLoginInfo } from '../../api/login.js'
import crypt from '../../utils/index.js'
import cryptoJs from '../../common/crypto-js'

export default {
  state: {
    userInfo: {}, // 用户信息
    orgInfo: {}, // 组织信息
    token: ''	
  },
  mutations: {
    userInfo (state, userInfo) {
      state.userInfo = userInfo
    },
    orgInfo (state, orgInfo) {
      state.orgInfo = orgInfo
    },
    token (state, token) {
      state.token = token
    }	
  },
  actions: {
    // 用户登陆
    login ({ commit }, userInfo) {
      const { username, password } = userInfo
      let randomCode = Math.random().toString().substring(2)
      let lang = 'zh-CN'
	  let params={
	   	user:username,
	  	pwd:md5Encript(password, username.trim(), randomCode),
	  	lang:lang,
	  	randomCode:randomCode
	  }
	  params = {reuestParas:crypt.aesEncrypt(JSON.stringify(params), config.loginConfig.aesKey)}	  
      return new Promise((resolve, reject) => {
        Login(params).then(response => {			
          if (response.result === '1') {           
            commit('token', response.token)
			storage.set('userNo', params)            
            storage.set('token', response.token)
			wx.switchTab({
				url:"/pages/workSpace/index"
			})
			getUserLoginInfo().then(res=>{
				commit('userInfo', res.rows)
				storage.set('userInfo', res.rows)
				console.log('getUserLoginInfo ===>',res)
			})
            resolve(response)
          } else {
			uni.showToast({
				title:'账户密码错误',
				duration:2000,
				icon:'none'
			})
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
	// 重新获取用户token
	reloadToken({ commit }){
		let secretCode = storage.get('userNo') 
		console.log('secretCode',secretCode)
		if(!secretCode) {
			uni.showToast({
			    title: '账号密码失效请重新登陆',
				icon:'none',
			    duration: 2000
			});
			uni.navigateTo({
				url:"/pages/login/index"
			})
			return
		}
		Login(secretCode,'close').then(res=>{
			if(res.result === '1'){				
				commit('token', res.token)				
				storage.set('token', res.token)	
				getUserLoginInfo().then(result=>{
					console.log('getUserLoginInfo',result.rows)
					commit('userInfo', result.rows)
					storage.set('userInfo', result.rows)					
					// console.log('getUserLoginInfo ===>',res)
				})
				// uni.navigateTo({
				// 	url:"/pages/workSpace/index"
				// })				
				// uni.navigateTo({
				// 	url:'pages/views/carPreFlight/carPreDetails'
				// })
			} else {
				uni.showToast({
				    title: '账号密码失效请重新登陆',
					icon:'none',
				    duration: 2000
				});
				uni.navigateTo({
					url:"/pages/login/index"
				})
			}
		})
	},
    // 退出登陆
    logout ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout({ token: state.token }).then(() => {
          commit('userInfo', {})
          commit('orgInfo', {})
          commit('token', '')
          storage.set('userInfo', {})
          storage.set('orgInfo', {})
          storage.set('token', '')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 用户找回密码
    findpwd ({ commit }, userInfo) {
      const { username, password } = userInfo
      let randomCode = Math.random().toString().substring(2)
      let lang = 'zh-CN'
      return new Promise((resolve, reject) => {
        findpwd({
          user: username.trim(),
          pwd: md5Encript(password, username.trim(), randomCode),
          lang: lang,
          randomCode: randomCode
        }).then(response => {
          if (response.result === '1') {
            resolve()
          } else {
            reject(response)
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 移除token（从cookie中）
    resetToken ({ commit }) {
      return new Promise(resolve => {
        commit('userInfo', {})
        storage.set('userInfo', '')
        storage.set('token', '')
        resolve()
      })
    }
  }
}

//MD5加密
function md5(val){
	return cryptoJs.MD5(val).toString()
}

// 密码加密
function md5Encript (password, username, randomCode) {
  let pwd = md5(md5(md5(md5(md5(username + md5(md5(md5(password))))))) + randomCode)
  return pwd
}

// 获取用户组织架构信息
function queryOrgInfo (response, commit, resolve) {
  let fields = 'BRAND_CODE DLR_CODE DLR_ID DLR_NAME DLR_ORG_TYPE DLR_STATUS GROUP_CODE GROUP_ID OEM_CODE OEM_ID ORG_CODE EMP_ID ORG_ID '
  fields += 'ORG_NAME ORG_TYPE PARENT_DLR_CODE PARENT_DLR_ID PARENT_DLR_NAME POS_CODE POS_ID SOLUTION_ID COMPANY_ID UPDATEPWDTIME '
  fields += 'GROUP_NAME BRAND_CN AREA_ID AREA_CODE AREA_NAME'
  getOrgInfo({ query: 'query{getUserLoginInfo{' + fields + '}}' }, response.token)
    .then(res => {
      if (res.result === '1' && res.data && res.data.getUserLoginInfo) {
        // 本地存储用户组织架构信息
        var orgInfo = res.data.getUserLoginInfo
        orgInfo.empname = response.empname
        orgInfo.userid = response.userid
        orgInfo.username = response.username
        orgInfo.usertype = response.usertype
        commit('orgInfo', orgInfo)
        storage.set('orgInfo', orgInfo)
      }
      resolve()
    })
}